package com.zb.controller;

import com.zb.dto.OrderItemDto;
import com.zb.service.CartService;
import com.zb.util.TokenDecode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;

    @PostMapping("/add")
    public Integer add(@RequestParam Integer num ,@RequestParam String skuId){
        String username = TokenDecode.getUserInfo().get("username");
        return cartService.addCart(skuId,num,username);
    }

    @GetMapping("/list")
    public List<OrderItemDto>list(){
        String username = TokenDecode.getUserInfo().get("username");
        List<OrderItemDto>list=cartService.list(username).stream().map(item ->{
            OrderItemDto orderItemDto = new OrderItemDto();
            BeanUtils.copyProperties(item, orderItemDto);
            return orderItemDto;
        }).collect(Collectors.toList());
        return list;
    }

    @DeleteMapping("/remove")
    public Integer remove(@RequestParam String[] skuIds) {
        String username = TokenDecode.getUserInfo().get("username");
        return cartService.delete(skuIds, username);
    }


    @GetMapping("/buylist")
    public List<OrderItemDto> buyList(@RequestParam String[] skuIds) {
        String username = TokenDecode.getUserInfo().get("username");
        List<OrderItemDto> list = cartService.buyList(skuIds, username).stream().map(item -> {
            OrderItemDto orderItemDto = new OrderItemDto();
            BeanUtils.copyProperties(item, orderItemDto);
            return orderItemDto;
        }).collect(Collectors.toList());
        return list;
    }


}
